package com.czk;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/12/27 20:57
 */
public class NettyFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup nioEventLoopGroup=new NioEventLoopGroup(1);
        EventLoop next = nioEventLoopGroup.next();
        io.netty.util.concurrent.Future<Integer> future = (io.netty.util.concurrent.Future<Integer>) next.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("czkkkk");
        });

        // 主线程获取
//        System.out.println(Thread.currentThread().getName() + " 获取结果");
//        System.out.println("getNow " + future.getNow());
//        System.out.println("get " + future.get());


        // 异步线程获取
        // NIO线程中异步获取结果
        future.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Integer>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Integer> future) throws Exception {
                System.out.println(Thread.currentThread().getName() + " 获取结果");
                System.out.println("getNow " + future.get());
            }

        });

    }
}



class JDKFuture{
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadFactory threadFactory=new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"jdkFuture");
            }
        };
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10,10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), threadFactory);

        // 获得Future对象
        Future<Integer> future = executor.submit(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                TimeUnit.SECONDS.sleep(1);
                return 50;
            }
        });

        // 通过阻塞的方式，获得运行结果
        System.out.println(future.get());

    }


}
